﻿@page "/SysPay"
@using SelfService.ViewModel.SysPayVMs;
@using SelfService.Model.Models
@using SelfService.Model.Request
@inherits BasePage
@attribute [ActionDescription("支付管理", "SelfService.Controllers,SysPay")]

<WTSearchPanel OnSearch="@DoSearch">
    <ValidateForm Model="@_searchModel">
        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
            <BootstrapInput @bind-Value="@_searchModel.PatientName" />
            <BootstrapInput @bind-Value="@_searchModel.OutOrderNo"  />
            <BootstrapInput @bind-Value="@_searchModel.SerialsNumber"  />
            <Select @bind-Value="@_searchModel.PayTypeId" Items="@_allSysPayTypes" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.PayStatus" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.RefundStatus" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.Use" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.UseStatus" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.Sync" PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <WTDateRange @bind-Value="@_searchModel.PayTime"/>
        </Row>
    </ValidateForm>
</WTSearchPanel>

<Table @ref="_dataTable"
        TItem="SysPayView"
        OnQueryAsync="OnSearch"
        IsPagination="true"
        IsStriped="true"
        IsBordered="true"
        ShowRefresh="false"
        ShowToolbar="true"
        IsMultipleSelect="true" 
        ShowExtendButtons="true" 
        ShowExtendDeleteButton="false"
        ShowExtendEditButton="false"
        ExtendButtonColumnAlignment="Alignment.Left"
        IsExtendButtonsInRowHeader="true"
        ShowDefaultButtons="false"
        style="margin-top:10px;">
    <TableColumns>
        <TableColumn @bind-Field="@context.PatientName"/>
        <TableColumn @bind-Field="@context.IdCardNo"/>
        <TableColumn @bind-Field="@context.CardNo"/>
        <TableColumn @bind-Field="@context.PayTypeName"/>
        <TableColumn @bind-Field="@context.Amount" FormatString="0.00"/>
        <TableColumn @bind-Field="@context.OutOrderNo"/>
        <TableColumn @bind-Field="@context.SerialsNumber"/>
        <TableColumn @bind-Field="@context.PayStatus"/>
        <TableColumn @bind-Field="@context.Use"/>
        <TableColumn @bind-Field="@context.UseStatus"/>
        <TableColumn @bind-Field="@context.RefundStatus"/>
        <TableColumn @bind-Field="@context.IsSync"/>
        <TableColumn @bind-Field="@context.PayTime" Sortable="true" FormatString="yyyy-MM-dd HH:mm:ss"/>
        <TableColumn @bind-Field="@context.CreateTime" Sortable="true" FormatString="yyyy-MM-dd HH:mm:ss"/>
    </TableColumns>
    <TableToolbarTemplate>
        @if (IsAccessable("/api/SysPay/BatchDelete"))
        {
            <TableToolbarPopconfirmButton
                TItem="SysPayView"
                Color="Color.Primary"
                Icon="fa fa-fw fa-trash-o" 
                Text="@WtmBlazor.Localizer["Sys.BatchDelete"]"
                OnConfirm="@OnBatchDeleteClick" 
                Content="@WtmBlazor.Localizer["Sys.BatchDeleteConfirm"]" 
                CloseButtonText="@WtmBlazor.Localizer["Sys.Close"]"
                ConfirmButtonText="@WtmBlazor.Localizer["Sys.BatchDelete"]" 
                ConfirmButtonColor="Color.Danger" />
        }
        @if (IsAccessable("/api/SysPay/ExportExcel"))
        {
            <TableToolbarButton 
                TItem="SysPayView" 
                Color="Color.Primary" 
                Icon="fa fa-fw fa-download" 
                Text="@WtmBlazor.Localizer["Sys.Export"]"
                OnClickCallback="@OnExportClick"
                IsAsync="true" />
        }
    </TableToolbarTemplate>
    <RowButtonTemplate>
        <div style="padding-right:10px;">
            @if (IsAccessable("/api/SysPay/{id}"))
            {
                <TableCellButton Size="Size.ExtraSmall" 
                                 Color="Color.Info" 
                                 Icon="fa fa-info" 
                                 Text="@WtmBlazor.Localizer["Sys.Details"]" 
                                 OnClick="()=>OnDetailsClick(context)" />
            }
            @if (IsAccessable("/api/SysPay/BatchDelete"))
            {
                <TableCellPopconfirmButton 
                    Icon="fa fa-trash-o" 
                    Text="@WtmBlazor.Localizer["Sys.Delete"]"
                    OnConfirm="() => OnDeleteClick(context)" 
                    Color="Color.Danger" 
                    Size="Size.ExtraSmall"
                    Content="@WtmBlazor.Localizer["Sys.DeleteConfirm"]" 
                    CloseButtonText="@WtmBlazor.Localizer["Sys.Close"]"
                    ConfirmButtonText="@WtmBlazor.Localizer["Sys.Delete"]" 
                    ConfirmButtonColor="Color.Danger" />
            }

            @if (IsAccessable("/api/SysPay/Refund"))
            {
                <TableCellPopconfirmButton 
                    Icon="fa fa-badge-dollar" 
                    Text="退款"
                    OnConfirm="() => OnRefundClick(context)" 
                    Color="Color.Warning" 
                    Size="Size.ExtraSmall"
                    Content="确定要发起退款吗?" 
                    CloseButtonText="取消"
                    ConfirmButtonText="退款" 
                    IsShow="context.RefundStatus != RefundStatusEnum.退款中 && context.RefundStatus != RefundStatusEnum.退款完成 && context.PayStatus == PayStatusEnum.支付成功 && context.UseStatus != UseStatusEnum.成功"
                    ConfirmButtonColor="Color.Warning" />
            }
        </div>
    </RowButtonTemplate>
</Table>

@code{

    private readonly SysPaySearcher _searchModel = new();
    private Table<SysPayView> _dataTable;
    private List<SelectedItem> _allSysPayTypes = new();

    protected override async Task OnInitializedAsync()
    {
        _allSysPayTypes = await WtmBlazor.Api.CallItemsApi("/api/SysPay/GetSysPayTypes", placeholder: WtmBlazor.Localizer["Sys.All"]);
        await base.OnInitializedAsync();
    }

    private async Task<QueryData<SysPayView>> OnSearch(QueryPageOptions opts)
    {
        return await StartSearch<SysPayView>("/api/SysPay/Search", _searchModel, opts);
    }

    private void DoSearch()
    {
        _dataTable.QueryAsync();
    }

    private async Task OnDetailsClick(SysPayView item)
    {
        await OpenDialog<Details>(WtmBlazor.Localizer["Sys.Details"], x => x.id == item.ID.ToString());
    }

    private async Task OnBatchDeleteClick()
    {
        if (_dataTable.SelectedRows.Any() == true)
        {
            await PostsData(_dataTable.SelectedRows.Select(x => x.ID).ToList(), $"/api/SysPay/batchDelete", (s) => WtmBlazor.Localizer["Sys.BatchDeleteSuccess", s]);
            await _dataTable.QueryAsync();
        }
        else
        {
            await WtmBlazor.Toast.Information(WtmBlazor.Localizer["Sys.Info"], WtmBlazor.Localizer["Sys.SelectOneRowMin"]);
        }
    }

    private async Task OnDeleteClick(SysPayView item)
    {
        await PostsData(new List<string> { item.ID.ToString() }, $"/api/SysPay/batchDelete", (s) => "Sys.OprationSuccess");
        await _dataTable.QueryAsync();
    }
    
    private async Task OnRefundClick(SysPayView item)
    {
        var postData = new PayRefundRequest()
        {
            PayId = item.ID
        };
        var result = await WtmBlazor.Api.CallAPI<Result<SysPay>>($"/api/SysPay/Refund", HttpMethodEnum.POST, postData);
        if (result?.Data.Code == 200)
        {
            await WtmBlazor.Toast.Success("提示", $"退款请求已经发起, 退款信息:用户[{item.PatientName}], 金额:￥{item.Amount}元, 请稍后查询结果！");
        }
        else
        {
            await WtmBlazor.Toast.Success("提示", $"退款失败, {result?.Data?.Message}, 退款信息:用户[{item.PatientName}]金额￥{item.Amount}元");
        }
        await _dataTable.QueryAsync();
    }

    private async Task OnExportClick(IEnumerable<SysPayView> items)
    {
        if (_dataTable.SelectedRows?.Any() == true)
        {
            await Download("/api/SysPay/ExportExcelByIds", _dataTable.SelectedRows.Select(x => x.ID.ToString()).ToList());
        }
        else
        {
            await Download("/api/SysPay/ExportExcel", _searchModel);
        }
    }
}
